<script setup lang="ts">
import { Modal } from 'ant-design-vue'
import { ColumnHeightOutlined, PlusOutlined, ReloadOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons-vue'
import type { MenuProps, PaginationProps, TableProps } from 'ant-design-vue'
import type { ConsultTableFormModel, ConsultTableModel } from '~@/api/list/table-list'
import { getListApi } from '~@/api/list/table-list'
import {FormState, userDeleteApi, userSaveApi, userUpdateApi} from '~@/api/common/user'
import UserRoleBind from './user-role-bind.vue'

const message = useMessage()
const columns = shallowRef([
  {
    title: '#',
    dataIndex: 'id',
  },
  {
    title: '用户名称',
    dataIndex: 'username',
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
  },
  {
    title: '年龄',
    dataIndex: 'age',
  },
  {
    title: '电话',
    dataIndex: 'phone',
  },
  {
    title: '最后登录时间',
    dataIndex: 'lastLoginTime',
    width: 200,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
  },
])
const loading = shallowRef(false)
const total = ref(0)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `总数据位：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef<ConsultTableModel[]>([])
const formModel = reactive<ConsultTableFormModel>({
  username: '',
  phone: '',
  nickname: '',
})

const tableSize = ref<string[]>(['large'])
const sizeItems = ref<MenuProps['items']>([
  {
    key: 'large',
    label: '默认',
    title: '默认',
  },
  {
    key: 'middle',
    label: '中等',
    title: '中等',
  },
  {
    key: 'small',
    label: '紧凑',
    title: '紧凑',
  },
])
const open = ref(false)
const roleBindOpen = ref(false)
const currentUserId = ref(null)
const currentUsername = ref('')
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getListApi({
      ...formModel,
      current: pagination.current,
      pageSize: pagination.pageSize,
    })
    dataSource.value = data.list ?? []
    total.value = data.total ?? 0
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

async function onSearch() {
  pagination.current = 1
  await init()
}

async function onReset() {
  // 清空所有参数重新请求
  formModel.username = ''
  formModel.nickname = ''
  formModel.phone = ''
  await init()
}

/**
 * 删除功能
 *  @param record
 *
 */
async function handleDelete(record: ConsultTableModel) {
  const close = message.loading('删除中......')
  try {
    const res = await userDeleteApi(record!.id)
    if (res.code === 200)
      await init()
    message.success('删除成功')
  }
  catch (e) {
    console.log(e)
  }
  finally {
    close()
  }
}

function handleUpdate(record: ConsultTableModel) {
  formState = record
  open.value = true
}

function handleAdd() {
  formState = {}
  open.value = true
}

// 打开角色绑定弹窗
function handleRoleBind(record: ConsultTableModel) {
  currentUserId.value = record.id
  currentUsername.value = record.username
  roleBindOpen.value = true
}

// 关闭角色绑定弹窗
function handleRoleBindClose() {
  roleBindOpen.value = false
}

// 角色绑定成功回调
function handleRoleBindSuccess() {
  // 可以在这里刷新用户列表或进行其他操作
  message.success('角色绑定成功')
}

/**
 * 新增事件
 *
 */
async function handleOk() {
  if (formState.id === undefined) {
    const { data } = await userSaveApi(formState)
    if (data === 1) {
      message.success('新增成功')
      open.value = false
      Modal.destroyAll()
      init()
    }
    else {
      message.error('新增失败，请重试')
    }
  }
  else {
    const { data } = await userUpdateApi(formState)
    if (data === 1) {
      message.success('修改成功')
      open.value = false
      Modal.destroyAll()
      init()
    }
    else {
      message.error('修改失败，请重试')
    }
  }
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

onMounted(() => {
  init()
})

let formState = reactive<FormState>({
  username: '',
  password: '',
  userSex: '',
  age: '',
  address: '',
  nickname: '',
  email: '',
  phone: '',
  id: null,
})

const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="8">
            <a-form-item name="username" label="用户名称">
              <a-input v-model:value="formModel.username" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="nickname" label="昵称">
              <a-input v-model:value="formModel.nickname" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="phone" label="电话">
              <a-input v-model:value="formModel.phone" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :span="24" style="text-align: right">
          <a-col :span="24">
            <a-space flex justify-end w-full>
              <a-button :loading="loading" type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button :loading="loading" @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="查询表格">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination" :size="tableSize[0] as TableProps['size']">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
              <div flex gap-2>
                <a c-blue @click="handleUpdate(scope?.record as ConsultTableModel)">
                  修改
                </a>
                <a c-error @click="handleDelete(scope?.record as ConsultTableModel)">
                  删除
                </a>
                <a c-primary @click="handleRoleBind(scope?.record as ConsultTableModel)">
                  绑定角色
                </a>
              </div>
            </template>
        </template>
      </a-table>
    </a-card>

    <a-modal v-model:open="open" title="用户编辑" width="400px" @ok="handleOk">
      <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        autocomplete="off"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="formState.username" />
        </a-form-item>
        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password v-model:value="formState.password" />
        </a-form-item>
        <a-form-item
          label="昵称"
          name="nickname"
          :rules="[{ required: true, message: '请输入昵称' }]"
        >
          <a-input v-model:value="formState.nickname" />
        </a-form-item>
        <a-form-item
          label="性别"
          name="userSex"
          :rules="[{ required: true, message: '请选择性别' }]"
        >
          <a-select v-model:value="formState.userSex" placeholder="请选择性别">
            <a-select-option value="男">
              男
            </a-select-option>
            <a-select-option value="女">
              女
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="年龄"
          name="age"
          :rules="[{ required: true, message: '请输入年龄' }]"
        >
          <a-input-number v-model:value="formState.age" style="width: 100%" />
        </a-form-item>
        <a-form-item
          label="电话"
          name="phone"
          :rules="[{ required: true, message: '请输入电话' }]"
        >
          <a-input v-model:value="formState.phone" />
        </a-form-item>
        <a-form-item
          label="邮箱"
          name="email"
          :rules="[{ required: true, message: '请输入邮箱' }]"
        >
          <a-input v-model:value="formState.email" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 角色绑定弹窗 -->
    <UserRoleBind
      :visible="roleBindOpen"
      :user-id="currentUserId"
      :username="currentUsername"
      @close="handleRoleBindClose"
      @success="handleRoleBindSuccess"
    />
  </page-container>
</template>
